<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\common\model;

use app\common\model\Base;
use think\Db;

class SystemUser extends Base {

    /**
     * @title 注册
     * @param type $post
     * @return type
     */
    public function reg($post) {

        $data['username'] = $post['username'] ?? '';
        $data['nickname'] = $post['nickname'] ?? '';
        $data['password'] = $post['password'] ?? '';
        $data['create_time'] = time();
        $data['update_time'] = time();


        $insert_id = db('system_user')->insertGetId($data);

        return $insert_id;
    }

    /**
     * @title 登录
     */
    public function login($post) {

        $username = $post['username'] ?? '';
        $password = $post['password'] ?? '';

        //echo my_md5($password); exit;

        $system_user = db('system_user')
                ->where('username', $username)
                ->where('password', my_md5($password))
                ->field('id,username,nickname')
                ->find();

        if ($system_user) {     
            
            // 生成一个随机token
            $token = uniqid();

            // 保存到浏览器端
            cookie(APP_THEME.'token_admin', $token);

            // 保存到服务器端
            cache($token, json_encode($system_user), 3600*24*7); // 保存登录一周
          
        } else {
            return '不存在的用户';
        }
    }

    public function model_where() {



        if (request()->get('keyword'))
            $this->where('nickname', 'like', '%' . request()->get('keyword') . '%');

        $this->order('id desc');

        return $this;
    }

}
